﻿
#region Using

using GalaSoft.MvvmLight.Command;
using NetBay.Core.BusinessEntities;
using NetBay.Core.BusinessEntities.Connectors;
using Rio.Framework.Localisation;
using Rio.Manager.Application.ViewModel.BaseClass;
using Rio.Framework.Pages;
using System;
using Rio.Applications.Web.Services;
using System.Collections.ObjectModel;
using System.ServiceModel.DomainServices.Client;
using System.Linq;
using GalaSoft.MvvmLight.Messaging;
using NetBay.Core.Silverlight.Tools;

#endregion Using

namespace Rio.Manager.Application.ViewModel.Administration
{
    public class ConnectorAddTabViewModel : TabViewModelBase
    {
        #region Fields

        public RelayCommand InitializationCommand { get; set; }
        public RelayCommand AddRowCommand { get; set; }
        public RelayCommand UpdateConnector { get; set; }
        public RelayCommand SaveConnector { get; set; }
        public RelayCommand CloseConnector { get; set; }
        
        private ObservableCollection<Connector> _ConnectorInformationToUpdate;
        private string _ConnectorTitleAdd;
        private string _organizationLabel;
        private string _folderTypeLabel;
        private string _ConnectorNameAddTitle;
        private string _ConnectorNameAdd;
        private string _ConnectorDescriptionAddTitle;
        private string _ConnectorDescriptionAdd;
        private string _ConnectorGeneralInformationAddTitle;
        private string _ConnectorCorrespondencesAddTitle;
        private ObservableCollection<ConnectorCorrespondence> _ConnectorCorrespondenceList;
        private ObservableCollection<ConnectorCorrespondence> _ConnectorCorrespondenceListSelected;
        private string _HeaderCorrespondenceIndexName;
        private string _HeaderCorrespondenceIndexPosition;
        private string _HeaderCorrespondenceIndexDescription;
        private ObservableCollection<ConnectorParameters> _ConnectorParameterList;
        private string _ConnectorParametersAddTitle;
        private string _HeaderParametersERP;
        private string _HeaderParametersRIO;
        private string _HeaderParametersDescription;
        private string _Button_Save_Connector;
        private string _Button_Update_Connector;
        private string _Button_Close_Connector;
        private string _Button_Delete_Connector_Parameter;
        private string _Button_Validate_Connector_Parameter;
        private Boolean _IsEnabledAddConnectorButton;
        private Boolean _IsEnabledUpdateConnectorButton;
        private Boolean _IsModifyMode;
        private Boolean _IsEditingradGridView_Parameters_Add;

        #endregion Fields

        #region Properties

        public string ConnectorTitleAdd
        {
            get { return _ConnectorTitleAdd; }
            set
            {
                _ConnectorTitleAdd = value;
                RaisePropertyChanged("ConnectorTitleAdd");
            }
        }

        public override FolderType SelectedFolderType
        {
            get { return base.SelectedFolderType; }
            set
            {
                base.SelectedFolderType = value;
                RaisePropertyChanged("SelectedFolderType");
                if (value != null && value.Identifier > 0)
                {                    
                    GetFolderTypeIndexes();
                }
            }
        }

        public override Organization SelectedOrganization
        {
            get { return base.SelectedOrganization; }
            set
            {               
                base.SelectedOrganization = value;
                RaisePropertyChanged("SelectedOrganization");               
            }
        }        

        public string OrganizationLabel
        {
            get { return _organizationLabel; }
            set
            {
                _organizationLabel = value;
                RaisePropertyChanged("OrganizationLabel");
            }
        }

        public string FolderTypeLabel
        {
            get { return _folderTypeLabel; }
            set
            {
                _folderTypeLabel = value;
                RaisePropertyChanged("FolderTypeLabel");
            }
        }

        public string ConnectorNameAddTitle
        {
            get { return _ConnectorNameAddTitle; }
            set
            {
                _ConnectorNameAddTitle = value;
                RaisePropertyChanged("ConnectorNameAddTitle");
            }
        }

        public string ConnectorDescriptionAddTitle
        {
            get { return _ConnectorDescriptionAddTitle; }
            set
            {
                _ConnectorDescriptionAddTitle = value;
                RaisePropertyChanged("ConnectorDescriptionAddTitle");
            }
        }

        public string ConnectorCorrespondencesAddTitle
        {
            get { return _ConnectorCorrespondencesAddTitle; }
            set
            {
                _ConnectorCorrespondencesAddTitle = value;
                RaisePropertyChanged("ConnectorCorrespondencesAddTitle");
            }
        }

        public string ConnectorParametersAddTitle
        {
            get { return _ConnectorParametersAddTitle; }
            set
            {
                _ConnectorParametersAddTitle = value;
                RaisePropertyChanged("ConnectorParametersAddTitle");
            }
        }

        public string ConnectorGeneralInformationAddTitle
        {
            get { return _ConnectorGeneralInformationAddTitle; }
            set
            {
                _ConnectorGeneralInformationAddTitle = value;
                RaisePropertyChanged("ConnectorGeneralInformationAddTitle");
            }
        }

        public string ConnectorNameAdd
        {
            get { return _ConnectorNameAdd; }
            set
            {
                _ConnectorNameAdd = value;
                RaisePropertyChanged("ConnectorNameAdd");
            }
        }

        public string ConnectorDescriptionAdd
        {
            get { return _ConnectorDescriptionAdd; }
            set
            {
                _ConnectorDescriptionAdd = value;
                RaisePropertyChanged("ConnectorDescriptionAdd");
            }
        }

        public string HeaderCorrespondenceIndexName
        {
            get { return _HeaderCorrespondenceIndexName; }
            set
            {
                _HeaderCorrespondenceIndexName = value;
                RaisePropertyChanged("HeaderCorrespondenceIndexName");
            }
        }

        public string HeaderCorrespondenceIndexPosition
        {
            get { return _HeaderCorrespondenceIndexPosition; }
            set
            {
                _HeaderCorrespondenceIndexPosition = value;
                RaisePropertyChanged("HeaderCorrespondenceIndexPosition");
            }
        }

        public string HeaderCorrespondenceIndexDescription
        {
            get { return _HeaderCorrespondenceIndexDescription; }
            set
            {
                _HeaderCorrespondenceIndexDescription = value;
                RaisePropertyChanged("HeaderCorrespondenceIndexDescription");
            }
        }

        public string HeaderParametersERP
        {
            get { return _HeaderParametersERP; }
            set
            {
                _HeaderParametersERP = value;
                RaisePropertyChanged("HeaderParametersERP");
            }
        }

        public string HeaderParametersRIO
        {
            get { return _HeaderParametersRIO; }
            set
            {
                _HeaderParametersRIO = value;
                RaisePropertyChanged("HeaderParametersRIO");
            }
        }

        public string HeaderParametersDescription
        {
            get { return _HeaderParametersDescription; }
            set
            {
                _HeaderParametersDescription = value;
                RaisePropertyChanged("HeaderParametersDescription");
            }
        }

        public ObservableCollection<Connector> ConnectorInformationToUpdate
        {
            get { return _ConnectorInformationToUpdate; }
            set
            {
                _ConnectorInformationToUpdate = value;
                RaisePropertyChanged("ConnectorInformationToUpdate");
            }
        }

        public ObservableCollection<ConnectorCorrespondence> ConnectorCorrespondenceList
        {
            get { return _ConnectorCorrespondenceList; }
            set
            {
                _ConnectorCorrespondenceList = value;
                RaisePropertyChanged("ConnectorCorrespondenceList");
            }
        }

        public ObservableCollection<ConnectorCorrespondence> ConnectorCorrespondenceListSelected
        {
            get { return _ConnectorCorrespondenceListSelected; }
            set
            {
                _ConnectorCorrespondenceListSelected = value;
                RaisePropertyChanged("ConnectorCorrespondenceListSelected");
            }
        }

        public ObservableCollection<ConnectorParameters> ConnectorParameterList
        {
            get { return _ConnectorParameterList; }
            set
            {
                _ConnectorParameterList = value;
                RaisePropertyChanged("ConnectorParameterList");
            }
        }

        public string Button_Save_Connector
        {
            get { return _Button_Save_Connector; }
            set
            {
                _Button_Save_Connector = value;
                RaisePropertyChanged("Button_Save_Connector");
            }
        }

        public string Button_Update_Connector
        {
            get { return _Button_Update_Connector; }
            set
            {
                _Button_Update_Connector = value;
                RaisePropertyChanged("Button_Update_Connector");
            }
        }

        public string Button_Close_Connector
        {
            get { return _Button_Close_Connector; }
            set
            {
                _Button_Close_Connector = value;
                RaisePropertyChanged("Button_Close_Connector");
            }
        }

        public string Button_Delete_Connector_Parameter
        {
            get { return _Button_Delete_Connector_Parameter; }
            set
            {
                _Button_Delete_Connector_Parameter = value;
                RaisePropertyChanged("Button_Delete_Connector_Parameter");
            }
        }

        public string Button_Validate_Connector_Parameter
        {
            get { return _Button_Validate_Connector_Parameter; }
            set
            {
                _Button_Validate_Connector_Parameter = value;
                RaisePropertyChanged("Button_Validate_Connector_Parameter");
            }
        }

        public Boolean IsEnabledAddConnectorButton
        {
            get { return _IsEnabledAddConnectorButton; }
            set
            {
                _IsEnabledAddConnectorButton = value;
                RaisePropertyChanged("IsEnabledAddConnectorButton");
            }
        }

        public Boolean IsEnabledUpdateConnectorButton
        {
            get { return _IsEnabledUpdateConnectorButton; }
            set
            {
                _IsEnabledUpdateConnectorButton = value;
                RaisePropertyChanged("IsEnabledUpdateConnectorButton");
            }
        }

        public Boolean IsModifyMode
        {
            get { return _IsModifyMode; }
            set
            {
                _IsModifyMode = value;                
                RaisePropertyChanged("IsModifyMode");
            }
        }

        public Boolean IsEditingradGridView_Parameters_Add
        {
            get { return _IsEditingradGridView_Parameters_Add; }
            set
            {
                _IsEditingradGridView_Parameters_Add = value;
                RaisePropertyChanged("IsEditingradGridView_Parameters_Add");
            }
        }

        #endregion Properties

        #region Constructor and Initialization

        public ConnectorAddTabViewModel()
            : base()
        {
            CanCloseTab = true;

            //Icon.
            TabIcon = new Uri("/Rio.Manager.Application;component/Assets/Images/Connector_Onglet_Add.png", UriKind.Relative);          
        }

        /// <summary>Inits the commands.</summary>
        public override void InitCommands()
        {
            //Command initialization.
            InitializationCommand = new RelayCommand(Initialization);
            AddRowCommand = new RelayCommand(AddConnectorParameterGridView);
            UpdateConnector = new RelayCommand(UpdateAnConnector);
            SaveConnector = new RelayCommand(SaveNewConnector);
            CloseConnector = new RelayCommand(CloseAddConnector);
        }

        /// <summary>Initializations this instance.</summary>
        private void Initialization()
        {
            InitLabels();
            InitsProperties();
            InitsButton();            
        }
        
        /// <summary>Inits the labels.</summary>
        public override void InitLabels()
        {
            //Label Initialization.
            if (IsModifyMode == false)
            {
                //Adding mode.
                TabTitle = Resx.GetLabel(ResxRioManager.CONNECTOR_ADD);
                TabIcon = new Uri("/Rio.Manager.Application;component/Assets/Images/Connector_Onglet_Add.png", UriKind.Relative);
                ConnectorTitleAdd = Resx.GetLabel(ResxRioManager.CONNECTOR_TITLE_ADD);
            }
            else
            {
                //Modify mode.
                TabTitle = Resx.GetLabel(ResxRioManager.CONNECTOR_UPDATE);
                TabIcon = new Uri("/Rio.Manager.Application;component/Assets/Images/Connector_Onglet_Manage.png", UriKind.Relative);
                ConnectorTitleAdd = Resx.GetLabel(ResxRioManager.CONNECTOR_TITLE_UPDATE);
            }               
            OrganizationLabel = Resx.GetLabel(ResxCommon.ORGANIZATION);
            FolderTypeLabel = Resx.GetLabel(ResxCommon.FOLDER_TYPE);            
            ConnectorGeneralInformationAddTitle = Resx.GetLabel(ResxRioManager.CONNECTOR_GENERAL_INFORMATION_ADD);
            ConnectorNameAddTitle = Resx.GetLabel(ResxRioManager.CONNECTOR_NAME_ADD);
            ConnectorDescriptionAddTitle = Resx.GetLabel(ResxRioManager.CONNECTOR_DESCRIPTION_ADD);
            ConnectorCorrespondencesAddTitle = Resx.GetLabel(ResxRioManager.CONNECTOR_CORRESPONDENCES_ADD);
            ConnectorParametersAddTitle = Resx.GetLabel(ResxRioManager.CONNECTOR_PARAMETERS_ADD);
            HeaderCorrespondenceIndexName = Resx.GetLabel(ResxRioManager.CONNECTOR_CORRESPONDENCE_INDEX_NAME);
            HeaderCorrespondenceIndexPosition = Resx.GetLabel(ResxRioManager.CONNECTOR_CORRESPONDENCE_INDEX_POSITION);
            HeaderCorrespondenceIndexDescription = Resx.GetLabel(ResxRioManager.CONNECTOR_CORRESPONDENCE_INDEX_DESCRIPTION);
            HeaderParametersERP = Resx.GetLabel(ResxRioManager.CONNECTOR_PARAMETERS_CUSTOMER);
            HeaderParametersRIO = Resx.GetLabel(ResxRioManager.CONNECTOR_PARAMETERS_RIO);
            HeaderParametersDescription = Resx.GetLabel(ResxRioManager.CONNECTOR_PARAMETERS_DESCRIPTION);
            Button_Save_Connector = Resx.GetLabel(ResxRioManager.BUTTON_SAVE_CONNECTOR);
            Button_Update_Connector = Resx.GetLabel(ResxRioManager.BUTTON_UPDATE_CONNECTOR);
            Button_Close_Connector = Resx.GetLabel(ResxRioManager.BUTTON_CLOSE_CONNECTOR);
            Button_Delete_Connector_Parameter = Resx.GetLabel(ResxCommon.DELETE);
            Button_Validate_Connector_Parameter = Resx.GetLabel(ResxCommon.VALIDATE);
        }

        /// <summary>Initialize properties</summary>
        public void InitsProperties()
        {
            //RadGridView parameters connector list.
            IsEditingradGridView_Parameters_Add = false;

            //Clean or Initialize properties. 
            if (IsModifyMode == false)
            {
                //Adding Mode.
                SelectedOrganization = new Organization();
                SelectedFolderType = new FolderType();
                ConnectorCorrespondenceList = new ObservableCollection<ConnectorCorrespondence>();
                ConnectorCorrespondenceListSelected = new ObservableCollection<ConnectorCorrespondence>();
                ConnectorParameterList = new ObservableCollection<ConnectorParameters>();
                ConnectorInformationToUpdate = new ObservableCollection<Connector>();
                ConnectorNameAdd = "";
                ConnectorDescriptionAdd = "";
            }
            else
            {                
                if (ConnectorParameterList.Count() != 0)
                {
                    ObservableCollection<ConnectorParameters> l_oConnectorParametersList = new ObservableCollection<ConnectorParameters>();
                    foreach (ConnectorParameters l_oConnectorParameters in ConnectorParameterList)
                    {
                        ConnectorParameters l_oConnectorParametersTemp = new ConnectorParameters();
                        l_oConnectorParametersTemp.ConnectorCustomerParam = l_oConnectorParameters.ConnectorCustomerParam;
                        l_oConnectorParametersTemp.ConnectorRioParam = l_oConnectorParameters.ConnectorRioParam;
                        l_oConnectorParametersTemp.ConnectorDescriptionParam = l_oConnectorParameters.ConnectorDescriptionParam;
                        l_oConnectorParametersTemp.ConnectorParamId = l_oConnectorParameters.ConnectorParamId;
                        l_oConnectorParametersList.Add(l_oConnectorParametersTemp);
                    }
                    ConnectorParameterList = l_oConnectorParametersList;
                }
            }
        }

        /// <summary>Show modify or create connector button.</summary>
        public void InitsButton()
        {
            //Button isn't enabled.
            IsEnabledAddConnectorButton = false;
            IsEnabledUpdateConnectorButton = false;

            //Show add or modify connector button.
            if (IsModifyMode == false)
            {
                //Adding Mode.
                IsEnabledAddConnectorButton = true;
            }
            else
            {
                //Modify Mode.
                IsEnabledUpdateConnectorButton = true;
            }                     
        }

        /// <summary>Inits the connector table.</summary>
        public void InitEmptyConnectorTable()
        {
            //Connector tables Initialization for the folder type selected.
            //Connector folder type indexes correspondence.
            BusinessEntitiesDomainContext l_oBEDomainContext = new BusinessEntitiesDomainContext();
            var query = l_oBEDomainContext.GetFolderTypeIndexCorrespondanceListQuery(SelectedFolderType.Name);
            l_oBEDomainContext.Load(query, GetFolderTypeCorrespondenceList, null);

            //Built connector folder type parameters.
            ConnectorParameterList = new ObservableCollection<ConnectorParameters>();

            if (IsModifyMode)
            {
                ConnectorCorrespondenceList = ConnectorCorrespondenceListSelected;
            }
        }

        #endregion Constructor and Initialization

        #region Methods

        /// <summary>
        /// Needs to refresh consultation connector saved.
        /// </summary>
        private void NeedToRefreshConnectorConsultationList()
        {
            //Message send to connector consultation actualisation. --> ConnectorTabViewModel.cs
            Messenger.Default.Send<NotificationMessage>(new NotificationMessage("RefreshConsultConnector"));
        }

        /// <summary>Gets the folder type indexes to built the gridview.</summary>
        public void GetFolderTypeIndexes()
        {
            //Retrieves indexes folder type.
            if (SelectedFolderType != null && SelectedFolderType.Identifier > 0)
            {
                InitEmptyConnectorTable();
            }           
        }

        /// <summary>Gets the folder type index list.</summary>
        /// <param name="e">Index List</param>
        private void GetFolderTypeCorrespondenceList(LoadOperation<ConnectorCorrespondence> e)
        {
            if (!e.HasError)
            {
                //Initialization variable.
                ObservableCollection<ConnectorCorrespondence> l_oConnectorFolderTypeCorrespondencesIndexList = new ObservableCollection<ConnectorCorrespondence>();

                //Built connector folder type correspondence index list.
                foreach (ConnectorCorrespondence l_oConnectorCorrespondenceList in e.Entities)
                {
                    ConnectorCorrespondence l_oConnectorCorrespondenceTemp = new ConnectorCorrespondence();
                    l_oConnectorCorrespondenceTemp.ConnectorIndexCorrespondenceName = l_oConnectorCorrespondenceList.ConnectorIndexCorrespondenceName;
                    l_oConnectorCorrespondenceTemp.ConnectorIndexCorrespondencePosition = l_oConnectorCorrespondenceList.ConnectorIndexCorrespondencePosition;
                    if (IsModifyMode)
                    {
                        //Retrieves Connector Correspondence Index Save in db.
                        var l_sConnectorIndexDescription = from ConnectorIndex in ConnectorCorrespondenceListSelected
                                                           where ConnectorIndex.ConnectorIndexCorrespondencePosition == l_oConnectorCorrespondenceList.ConnectorIndexCorrespondencePosition
                                                           select new { ConnectorIndex.ConnectorIndexCorrespondenceDescription };
                        if (l_sConnectorIndexDescription.Count() != 0)
                        {
                            l_oConnectorCorrespondenceTemp.ConnectorIndexCorrespondenceDescription = l_sConnectorIndexDescription.FirstOrDefault().ConnectorIndexCorrespondenceDescription.ToString();
                        }
                        else
                        {
                            l_oConnectorCorrespondenceTemp.ConnectorIndexCorrespondenceDescription = l_oConnectorCorrespondenceList.ConnectorIndexCorrespondenceDescription;
                        }
                    }
                    else
                    {
                        l_oConnectorCorrespondenceTemp.ConnectorIndexCorrespondenceDescription = l_oConnectorCorrespondenceList.ConnectorIndexCorrespondenceDescription;
                    }                        
                l_oConnectorFolderTypeCorrespondencesIndexList.Add(l_oConnectorCorrespondenceTemp);
                }
                ConnectorCorrespondenceList = l_oConnectorFolderTypeCorrespondencesIndexList;

                //Select connector correpondex index who are save in the db.
                Messenger.Default.Send<NotificationMessage<ObservableCollection<ConnectorCorrespondence>>>(new NotificationMessage<ObservableCollection<ConnectorCorrespondence>>(ConnectorCorrespondenceList, String.Empty));
            }
        }

        /// <summary>Test to do before update or add an connector in the database.</summary>       
        private Boolean TestBeforeAddOrUpdateConnector()
        {
            //Variable initialization.
            Boolean l_bResult = true;            
            Boolean l_bIsEnabledAddConnectorButtonTemp = IsEnabledAddConnectorButton;
            Boolean l_bIsEnabledUpdateConnectorButtonTemp = IsEnabledUpdateConnectorButton;
                       
            //Connector Name and Description can't to be null.
            if (ConnectorNameAdd == "" || ConnectorDescriptionAdd == "")
            {                
                MessageBoxChildWindow L_oMessage = new MessageBoxChildWindow(String.Empty, Resx.GetLabel(ResxRioManager.CONNECTOR_ADD_NO_NAME_OR_DESCRIPTION), MessageBoxButtons.Ok, MessageBoxIcon.Warning);
                L_oMessage.Show();
                L_oMessage.Closed += (s, ev) =>
                {                   
                    l_bResult = false;
                    IsEnabledAddConnectorButton = l_bIsEnabledAddConnectorButtonTemp;
                    IsEnabledUpdateConnectorButton = l_bIsEnabledUpdateConnectorButtonTemp;
                };
                //Return.
                l_bResult = false;
            }
            //Connector Correspondence can't to be null.
            else if (ConnectorCorrespondenceListSelected.Count == 0)
            {              
                MessageBoxChildWindow L_oMessage = new MessageBoxChildWindow(String.Empty, Resx.GetLabel(ResxRioManager.CONNECTOR_ADD_NO_CORRESPONDENCE), MessageBoxButtons.Ok, MessageBoxIcon.Warning);
                L_oMessage.Show();
                L_oMessage.Closed += (s, ev) =>
                {
                    l_bResult = false;
                    IsEnabledAddConnectorButton = l_bIsEnabledAddConnectorButtonTemp;
                    IsEnabledUpdateConnectorButton = l_bIsEnabledUpdateConnectorButtonTemp;
                };  
                //Return.
                l_bResult = false;
            }
            //Connector parameters grid must to be validate.
            else if (IsEditingradGridView_Parameters_Add)
            {
                MessageBoxChildWindow L_oMessage = new MessageBoxChildWindow(String.Empty, Resx.GetLabel(ResxRioManager.CONNECTOR_MSG_PARAMETER_ISEDITING), MessageBoxButtons.Ok, MessageBoxIcon.Warning);
                L_oMessage.Show();
                L_oMessage.Closed += (s, ev) =>
                {
                    l_bResult = false;
                    IsEnabledAddConnectorButton = l_bIsEnabledAddConnectorButtonTemp;
                    IsEnabledUpdateConnectorButton = l_bIsEnabledUpdateConnectorButtonTemp;
                };
                //Return.
                l_bResult = false;      
            }
            //Connector parameter can't to be null on an rows only the descritpion can.
            else if (ConnectorParameterList.Count != 0)
            {
                if (ConnectorParameterList.Select(i => i.ConnectorCustomerParam).Any(i => String.IsNullOrWhiteSpace(i))
                || (ConnectorParameterList.Select(i => i.ConnectorRioParam).Any(i => String.IsNullOrWhiteSpace(i))))
                {
                    MessageBoxChildWindow L_oMessage = new MessageBoxChildWindow(String.Empty, Resx.GetLabel(ResxRioManager.CONNECTOR_ADD_PARAMETER_VALUE_NULL), MessageBoxButtons.Ok, MessageBoxIcon.Warning);
                    L_oMessage.Show();
                    L_oMessage.Closed += (s, ev) =>
                    {
                        l_bResult = false;
                        IsEnabledAddConnectorButton = l_bIsEnabledAddConnectorButtonTemp;
                        IsEnabledUpdateConnectorButton = l_bIsEnabledUpdateConnectorButtonTemp;
                    };
                    //Return.
                    l_bResult = false;                  
                }
            }

            //Test are good.
            return l_bResult;
        }

        /// <summary>Save connector correspondence.</summary>
        /// <param name="p_lConnectorId">The connector id.</param>
        private void SaveNewConnectorCorrespondence(long p_lConnectorId)
        {
            //Variable initialization.
            Boolean l_bIsEnabledAddConnectorButtonTemp = IsEnabledAddConnectorButton;
            Boolean l_bIsEnabledUpdateConnectorButtonTemp = IsEnabledUpdateConnectorButton;
            BusinessEntitiesDomainContext l_oBEDomainContext = new BusinessEntitiesDomainContext();
            MessageBoxChildWindow L_oMessage = new MessageBoxChildWindow();

            try
            {
                //Test on the connector.
                switch (p_lConnectorId)
                {
                    case -1:
                        //Connector Exists --> can't be save.
                        L_oMessage = new MessageBoxChildWindow(String.Empty, string.Format(Resx.GetLabel(ResxRioManager.CONNECTOR_EXISTS), ConnectorNameAdd).Replace("\\n", Environment.NewLine), MessageBoxButtons.Ok, MessageBoxIcon.Warning);
                        L_oMessage.Show();
                        L_oMessage.Closed += (s, ev) =>
                        {                           
                            IsEnabledAddConnectorButton = l_bIsEnabledAddConnectorButtonTemp;
                            IsEnabledUpdateConnectorButton = l_bIsEnabledUpdateConnectorButtonTemp;
                        };
                       break;

                    case 0:
                        //Connector doesn't added. 
                        L_oMessage = new MessageBoxChildWindow(String.Empty, string.Format(Resx.GetLabel(ResxRioManager.CONNECTOR_ADD_ERROR), ConnectorNameAdd).Replace("\\n", Environment.NewLine), MessageBoxButtons.Ok, MessageBoxIcon.Error);
                        L_oMessage.Show();
                        L_oMessage.Closed += (s, ev) =>
                        {                           
                            IsEnabledAddConnectorButton = l_bIsEnabledAddConnectorButtonTemp;
                            IsEnabledUpdateConnectorButton = l_bIsEnabledUpdateConnectorButtonTemp;
                        };
                        break;

                    default:
                        //Save Connector correspondence.                        
                        string l_oLstSerializeConnectorCorrespondenceToAdd = SerializationHelper.Serialize(ConnectorCorrespondenceListSelected);
                        l_oBEDomainContext.AddCorrespondenceConnector(l_oLstSerializeConnectorCorrespondenceToAdd,p_lConnectorId,SelectedOrganization.Identifier,SelectedFolderType.Identifier,
                                                                          result =>
                                                                          {
                                                                              if (result.HasError)
                                                                              {
                                                                                  DeleteConnector(p_lConnectorId, true);
                                                                              }
                                                                              else
                                                                              {
                                                                                  SaveNewConnectorParameters(p_lConnectorId);
                                                                              }
                                                                          },
                                                                            null);
                    break;
                }
            }
            catch (Exception ex)
            {
                //Error.
                L_oMessage = new MessageBoxChildWindow(String.Empty, string.Format(Resx.GetLabel(ResxRioManager.CONNECTOR_ADD_ERROR), ConnectorNameAdd) + Environment.NewLine + ex.Message, MessageBoxButtons.Ok, MessageBoxIcon.Error);
                L_oMessage.Show();
            }
        }

        /// <summary>Save connector Parameters.</summary>
        /// <param name="p_lConnectorId">The connector id.</param>
        private void SaveNewConnectorParameters(long p_lConnectorId)
        {
            try
            {
                if (ConnectorParameterList.Count != 0)
                {
                    //Variable initialization.
                    BusinessEntitiesDomainContext l_oBEDomainContext = new BusinessEntitiesDomainContext();

                    string l_oLstSerializeConnectorParametersToAdd = SerializationHelper.Serialize(ConnectorParameterList);
                    l_oBEDomainContext.AddParameterConnector(l_oLstSerializeConnectorParametersToAdd, p_lConnectorId,
                                 result =>
                                 {
                                     if (result.HasError)
                                     {
                                         DeleteConnector(p_lConnectorId, true);
                                     }
                                     else
                                     {
                                         SaveNewConnectorEnd();
                                     }
                                 },
                            null);
                }
                else
                {                    
                    SaveNewConnectorEnd();
                }
            }

            catch (Exception ex)
            {				
                //Error.
                MessageBoxChildWindow L_oMessage = new MessageBoxChildWindow(String.Empty, string.Format(Resx.GetLabel(ResxRioManager.CONNECTOR_ADD_ERROR), ConnectorNameAdd) + Environment.NewLine + ex.Message, MessageBoxButtons.Ok, MessageBoxIcon.Error);
                L_oMessage.Show();
            }
        }

        /// <summary>Save connector end.</summary>       
        private void SaveNewConnectorEnd()
        {           
           //Message.		 
           MessageBoxChildWindow L_oMessage = new MessageBoxChildWindow(String.Empty, string.Format(Resx.GetLabel(ResxRioManager.CONNECTOR_ADD_SUCCES), ConnectorNameAdd), MessageBoxButtons.Ok, MessageBoxIcon.Information);
           L_oMessage.Show();
           L_oMessage.Closed += (s, ev) =>
           {
               //Clean Data.
               InitsProperties();

               //Send message to refresh consultation connector if this table is open.
               NeedToRefreshConnectorConsultationList();

               //Close the add connector windows.
               CloseTab();      
           };
        }

        /// <summary>Update connector parameter.</summary>     
        private void UpdateConnectorEnd()
        {         
            //Message.		 
            MessageBoxChildWindow L_oMessage = new MessageBoxChildWindow(String.Empty, string.Format(Resx.GetLabel(ResxRioManager.CONNECTOR_UPDATE_SUCCES), ConnectorNameAdd), MessageBoxButtons.Ok, MessageBoxIcon.Information);
            L_oMessage.Show();
            L_oMessage.Closed += (s, ev) =>
            {
                //Clean Data.
                InitsProperties();

                //Send message to refresh consultation connector if this table is open.
                NeedToRefreshConnectorConsultationList();

                //Close the add connector windows.
                CloseTab();
            };
        }

        /// <summary>Update connector correspondence.</summary>
        /// <param name="p_lConnectorId">The connector id to update.</param>
        private void UpdateConnectorCorrespondence(long p_lConnectorId)
        {
            //Variable initialization.
            BusinessEntitiesDomainContext l_oBEDomainContext = new BusinessEntitiesDomainContext();
            MessageBoxChildWindow L_oMessage = new MessageBoxChildWindow();
            Boolean l_bIsEnabledAddConnectorButtonTemp = IsEnabledAddConnectorButton;
            Boolean l_bIsEnabledUpdateConnectorButtonTemp = IsEnabledUpdateConnectorButton;

            try
            {
                //Test on the connector.
                switch (p_lConnectorId)
                {
                    case -1:
                        //Connector Exists --> can't be save.
                        L_oMessage = new MessageBoxChildWindow(String.Empty, string.Format(Resx.GetLabel(ResxRioManager.CONNECTOR_EXISTS), ConnectorNameAdd).Replace("\\n", Environment.NewLine), MessageBoxButtons.Ok, MessageBoxIcon.Warning);
                        L_oMessage.Show();
                        L_oMessage.Closed += (s, ev) =>
                        {
                            IsEnabledAddConnectorButton = l_bIsEnabledAddConnectorButtonTemp;
                            IsEnabledUpdateConnectorButton = l_bIsEnabledUpdateConnectorButtonTemp;
                        };
                        break;

                    case 0:
                        //Connector doesn't added. 
                        L_oMessage = new MessageBoxChildWindow(String.Empty, string.Format(Resx.GetLabel(ResxRioManager.CONNECTOR_UPDATE_ERROR), ConnectorNameAdd).Replace("\\n", Environment.NewLine), MessageBoxButtons.Ok, MessageBoxIcon.Error);
                        L_oMessage.Show();
                        L_oMessage.Closed += (s, ev) =>
                        {
                            IsEnabledAddConnectorButton = l_bIsEnabledAddConnectorButtonTemp;
                            IsEnabledUpdateConnectorButton = l_bIsEnabledUpdateConnectorButtonTemp;
                        };
                        break;

                    default:
                        //Update Connector correspondence.
                        string l_sLstSerializeConnectorCorrespondenceToUpdate = SerializationHelper.Serialize(ConnectorCorrespondenceListSelected);
                        l_oBEDomainContext.AddCorrespondenceConnector(l_sLstSerializeConnectorCorrespondenceToUpdate, p_lConnectorId, SelectedOrganization.Identifier, SelectedFolderType.Identifier,
                                                                                  result =>
                                                                                  {
                                                                                      if (result.HasError)
                                                                                      {
                                                                                          DeleteConnector(p_lConnectorId, true);
                                                                                      }
                                                                                      else
                                                                                      {
                                                                                          UpdateConnectorParameters(p_lConnectorId);
                                                                                      }
                                                                                  },
                                                                                    null);
                        break;
                }
            }
            catch (Exception ex)
            {
                //Error.
                L_oMessage = new MessageBoxChildWindow(String.Empty, string.Format(Resx.GetLabel(ResxRioManager.CONNECTOR_UPDATE_ERROR), ConnectorNameAdd) + Environment.NewLine + ex.Message, MessageBoxButtons.Ok, MessageBoxIcon.Error);
                L_oMessage.Show();
            }
        }

        /// <summary>Update connector Parameters.</summary>
        /// <param name="p_lConnectorId">The connector id.</param>
        private void UpdateConnectorParameters(long p_lConnectorId)
        {
            try
            {
                if (ConnectorParameterList.Count != 0)
                {
                    //Variable initialization.
                    BusinessEntitiesDomainContext l_oBEDomainContext = new BusinessEntitiesDomainContext();

                    string l_sLstSerializeConnectorParametersToUpdate = SerializationHelper.Serialize(ConnectorParameterList);
                    l_oBEDomainContext.AddParameterConnector(l_sLstSerializeConnectorParametersToUpdate, p_lConnectorId, 
                                 result =>
                                 {
                                     if (result.HasError)
                                     {
                                         DeleteConnector(p_lConnectorId, true);
                                     }
                                     else
                                     {
                                         UpdateConnectorEnd();
                                     }
                                 },
                            null);
                }
                else
                {
                    UpdateConnectorEnd();
                }
            }

            catch (Exception ex)
            {
                //Error.
                MessageBoxChildWindow L_oMessage = new MessageBoxChildWindow(String.Empty, string.Format(Resx.GetLabel(ResxRioManager.CONNECTOR_UPDATE_ERROR), ConnectorNameAdd) + Environment.NewLine + ex.Message, MessageBoxButtons.Ok, MessageBoxIcon.Error);
                L_oMessage.Show(); 
            }
        }

        #endregion Methods

        #region Command

        /// <summary>Adds the connector parameter command.</summary>
        public void AddConnectorParameterGridView()
        {
            //Insert connector Parameters gridview rows.
            if (ConnectorParameterList == null)
            {
                ConnectorParameterList = new ObservableCollection<ConnectorParameters>();
            }

            //Grid is in editing mode.
            IsEditingradGridView_Parameters_Add = true;
        }

        /// <summary>Saves the new connector.</summary>
        public void SaveNewConnector()
        {           
            //Differents test before start connector updating.
            if (TestBeforeAddOrUpdateConnector())
            {
                //Save Connector Name and Description if don't exists.
                BusinessEntitiesDomainContext l_oBEDomainContext = new BusinessEntitiesDomainContext();
                l_oBEDomainContext.AddConnector(ConnectorNameAdd, ConnectorDescriptionAdd, result =>
                {
                    if (result.HasError)
                    {
                        DeleteConnector(result.Value.Value, true);
                    }
                    else
                    {
                        SaveNewConnectorCorrespondence(result.Value.Value);
                    }
                },
                null);
            }
        }

        /// <summary>Update an connector.</summary>
        public void UpdateAnConnector()
        {
            //Differents test before start connector updating.
            if (TestBeforeAddOrUpdateConnector())
            {
                //Update Connector Name and Description.
                BusinessEntitiesDomainContext l_oBEDomainContext = new BusinessEntitiesDomainContext();
                l_oBEDomainContext.UpdateNameAndDescriptionConnectorByConnectorId(ConnectorInformationToUpdate[0].ConnectorId, ConnectorNameAdd, ConnectorDescriptionAdd, result =>
                {
                    if (result.HasError)
                    {
                        //Error.
                        MessageBoxChildWindow L_oMessage = new MessageBoxChildWindow(String.Empty, string.Format(Resx.GetLabel(ResxRioManager.CONNECTOR_UPDATE_ERROR), ConnectorNameAdd).Replace("\\n", Environment.NewLine), MessageBoxButtons.Ok, MessageBoxIcon.Error);
                        L_oMessage.Show();
                    }
                    else
                    {
                        UpdateConnectorCorrespondence(result.Value.Value);
                    }
                },
                null);
            }             
        }

        /// <summary>Delete the connector.</summary>
        /// <param name="p_lConnectorID">Connector Id to delete</param>
        /// <param name="p_bMessageErrorAddConnector"></param> 
        public void DeleteConnector(long p_lConnectorID,Boolean p_bMessageErrorAddConnector)
        {
            //Delete Connector Id.
            BusinessEntitiesDomainContext l_oBEDomainContext = new BusinessEntitiesDomainContext();
            l_oBEDomainContext.DeleteConnectorByConnectorId(p_lConnectorID, result =>
            {
                if (result.HasError)
                {
                    if (p_bMessageErrorAddConnector == false)
                    {
                        //Error.
                        MessageBoxChildWindow L_oMessage = new MessageBoxChildWindow(String.Empty, Resx.GetLabel(ResxRioManager.CONNECTOR_DELETE_ERROR) + Environment.NewLine + result.Error.Message, MessageBoxButtons.Ok, MessageBoxIcon.Error);
                        L_oMessage.Show();
                    }
                }
                else
                    if (p_bMessageErrorAddConnector == false)
                    {                     
                        //Succes.
                        MessageBoxChildWindow L_oMessage = new MessageBoxChildWindow(String.Empty, Resx.GetLabel(ResxRioManager.CONNECTOR_DELETE_SUCCES), MessageBoxButtons.Ok, MessageBoxIcon.Information);
                        L_oMessage.Show();
                    }                    
            },
            null);
        }

        /// <summary>Closes the add connector windows.</summary>
        public void CloseAddConnector()
        {           
            //Close the add connector windows.
            CloseTab();
        }
              
        #endregion Command
    }
}
